<template>
  <div id="app">
    <MyHeader title="购物车" bgColor="#1d7bff" color="#fff"></MyHeader>
    <MyGoodsItem
      v-for="item in list"
      :goods="item"
      :key="item.id"
      @change="changeFn"
    ></MyGoodsItem>
    <MyFooter :list="list" @set="setFn"></MyFooter>
  </div>
</template>

<script>
// 引入组件
import MyHeader from "./components/MyHeader";
import MyFooter from "./components/MyFooter";
import MyGoodsItem from "./components/MyGoodsItem";
import axios from "axios";
export default {
  // 创建组件
  components: {
    MyHeader,
    MyFooter,
    MyGoodsItem,
  },
  data() {
    return {
      list: [],
    };
  },
  created() {
    this.Rendering();
    this.bus.$on("add", (value, id) => {
      // console.log(value);
      // console.log(id);
      const obj = this.list.find((item) => item.id === id);
      obj.goods_count = value + 1;
    });
    this.bus.$on("reduce", (value, id) => {
      // console.log(value);
      // console.log(id);
      const obj = this.list.find((item) => item.id === id);
      if (value > 1) {
        obj.goods_count = value - 1;
      }
    });
    this.bus.$on("change", (value, id) => {
      // console.log(value);
      // console.log(id);
      const obj = this.list.find((item) => item.id === id);
      if (value > 1) {
        obj.goods_count = value;
      } else {
        // 输入两次负数dom页面不变的情况涉及到了虚拟dom  因为 都是一 数据没有改变虚拟Dom不会更新
        // 这个时候需要强制更新MyCount组件
        obj.goods_count = 1;
      }
    });
  },
  methods: {
    async Rendering() {
      const res = await axios({
        method: "get",
        url: "https://www.escook.cn/api/cart",
      });
      console.log(res);
      const { list, status } = res.data;
      if (status === 200) {
        this.list = list;
      }
    },
    changeFn(id) {
      // console.log(id);
      const obj = this.list.find((item) => item.id === id);
      obj.goods_state = !obj.goods_state;
    },
    setFn(value) {
      this.list.forEach((item) => (item.goods_state = value));
    },
  },
};
</script>

<style>
#app {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
